package com.kaifamiao.demo.d0907;

import java.sql.*;

public class Util implements AutoCloseable {

    private Connection conn;
    private PreparedStatement statement;
    private ResultSet resultSet;


    private String url;
    private String user;
    private String password;

    public Util(String url){
        this.url = url;
    }

    public Util(String url, String user, String password){
        this.url = url;
        this.user = user;
        this.password = password;
    }

    public Connection getConnection() throws SQLException {
        if (conn == null){
            if (user == null){
                conn = DriverManager.getConnection(url);
            } else{
                conn = DriverManager.getConnection(url, user, password);
            }
        }
        return conn;
    }

    public ResultSet query(String sql, Object...params) throws SQLException {
        getConnection();

        statement = conn.prepareStatement(sql);

        // 设置参数
        for (int i = 0; i < params.length; i++) {
            statement.setObject(i + 1, params[i]);
        }

        resultSet = statement.executeQuery();
        return resultSet;
    }

    public int update(String sql, Object...params) throws SQLException{
        getConnection();

        statement = conn.prepareStatement(sql);

        // 设置参数
        for (int i = 0; i < params.length; i++) {
            statement.setObject(i + 1, params[i]);
        }

        return statement.executeUpdate();
    }

    public void close(){
        try {
            if (resultSet != null){
                resultSet.close();
                resultSet = null;
            }
            if (statement != null){
                statement.close();
                statement = null;
            }
            if (conn != null){
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
